package org.example.security.service;

import org.example.core.constant.TokenConstants;
import org.example.core.utils.JwtUtils;
import org.example.core.to.LoginUser;
import org.example.redis.service.RedisService;
import org.example.security.constant.SecurityRedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 小杰_cc
 * @version 1.0
 */

@Component
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createUserToken(LoginUser loginUser){
        // 缓存用户信息
        saveUserCache(loginUser);
        // jwt信息
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(TokenConstants.USER_ID,loginUser.getId());
        claims.put(TokenConstants.USER_NAME,loginUser.getUsername());

        // 生成令牌返回
        return JwtUtils.createUserToken(claims);
    }

    // 缓存管理员权限数据
    public void saveUserCache(LoginUser loginUser){
        redisService.setObject(SecurityRedisConstants.USER_TOKEN + loginUser.getId(), loginUser, TokenConstants.EXPIRATION, TimeUnit.MINUTES);
    }

    // 删除管理权限缓存
    public void deleteUserCache(String userId){
        redisService.deleteObject(SecurityRedisConstants.USER_TOKEN + userId);
    }

    // 刷新管理员权限缓存
    public boolean refreshUserCache(String userId){
        return redisService.setExpire(SecurityRedisConstants.USER_TOKEN + userId, TokenConstants.EXPIRATION, TimeUnit.MINUTES);
    }

    // 生成新token
    public String refreshUserToken(String userId, String username){
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(TokenConstants.USER_ID,userId);
        claims.put(TokenConstants.USER_NAME,username);

        // 生成令牌返回
        return JwtUtils.createUserToken(claims);
    }
}